<template>
  <div class="app-container">
    <!-- 顶部控制台 -->
    <div class="filter-container">
      <el-input class="filter-item" style="width: 200px; margin-left: 0px" size="mini" placeholder="讲师名称" v-model="form.searchTitle"/>
      <el-select class="filter-item" style="width: 120px" size="mini" v-model="form.searchStatus" @change="handlePageInit">
        <el-option v-for="item in pageData.searchStatusList" :key="item.value" :label="item.label" :value="item.value"/>
      </el-select>
      <el-button type="primary" size="mini" icon="el-icon-search" @click="handlePageInit">搜索</el-button>
      <el-button type="primary" size="mini" icon="el-icon-edit" @click="handleOpenSavePage">添加</el-button>
      <el-button type="success" size="mini" icon="el-icon-share" @click="handleBatchReleaseData" :disabled="form.selection.length < 1">批量发布</el-button>
    </div>
    <!-- 页面数据列表 -->
    <div class="data-table">
      <el-table :data="responseData.tableList"
                border style="width: 100%;"
                v-loading="pageData.loading"
                element-loading-text="拼命加载中"
                element-loading-spinner="el-icon-loading"
                element-loading-background="rgba(0, 0, 0, 0.8)"
                :header-cell-style="{ background: '#545C64', color: '#ffffff' }"
                @selection-change="handleTableSelection">
        <el-table-column type="selection" width="55" align="center"/>
        <el-table-column fixed="left" prop="lecturerId" label="讲师ID" width="320" align="center"/>
        <el-table-column prop="lecturerName" label="讲师名称" width="320" align="center"/>
        <el-table-column label="讲师头像" width="120" align="center">
          <template slot-scope="scope">
            <span v-if="scope.row.lecturerImage != null && scope.row.lecturerImage !== ''">
              <el-button size="small" width="120" type="success" @click="handleCheckInfo(scope)">预览</el-button>
            </span>
            <span v-else >无</span>
          </template>
        </el-table-column>
        <el-table-column label="可用状态" width="160" align="center">
          <template slot-scope="scope">
            <span v-if="scope.row.lecturerStatus === 0"><el-tag type="warning">下架</el-tag></span>
            <span v-if="scope.row.lecturerStatus === 1"><el-tag type="success">发布</el-tag></span>
            <span v-if="scope.row.lecturerStatus === 2"><el-tag type="danger">已删除</el-tag></span>
          </template>
        </el-table-column>
        <el-table-column prop="lecturerCreateTime" label="创建时间" width="320" align="center"/>
        <el-table-column fixed="right" label="操作" width="220" align="center">
          <template slot-scope="scope">
            <el-button type="primary" size="mini" @click="handleOpenEditPage(scope)">编辑</el-button>
            <el-button v-if="scope.row.lecturerStatus === 0" size="mini" type="success" @click="handleUpdateDataStatus(scope, 1)">发布</el-button>
            <el-button v-if="scope.row.lecturerStatus === 1" size="mini" type="warning" @click="handleUpdateDataStatus(scope, 0)">下架</el-button>
            <el-button size="mini" type="danger" @click="handleDeleteData(scope)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!--分页器-->
    <div style="margin-top: 20px">
      <div class="block" style="width: 100%; text-align: center">
        <el-pagination
          layout="total, sizes, prev, pager, next, jumper"
          :current-page="form.pageNum"
          :page-size="form.pageSize"
          :total="form.total"
          :page-sizes="[12, 50, 100, 200]"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange">
        </el-pagination>
      </div>
    </div>
    <!--图片预览隐藏域-->
    <div style="margin-top: 20px">
      <el-dialog title="图片预览" :visible.sync="pageData.checkPanelStatus">
        <el-card :body-style="{ padding: '0px' }">
          <div>
            <div>
              <img :src="pageData.checkPanelInfo">
            </div>
          </div>
        </el-card>
      </el-dialog>
    </div>
    <!--讲师新增/修改隐藏域-->
    <div style="margin-top: 20px">
      <el-dialog :title="pageData.formPanelTitle" :visible.sync="pageData.formPanelStatus" size="medium"
                 :before-close="handleCloseSavePage">
        <el-form :model="form" label-width="80px" ref="form" :rules="formRules">
          <!--讲师昵称-->
          <el-row :gutter="0">
            <el-col :span="15">
              <el-row :gutter="0">
                <el-col :span="24">
                  <el-form-item prop="lecturerName" label="讲师名称">
                    <el-input placeholder="请输入讲师名称" v-model="form.lecturerName" class="filter-item" auto-complete="off"/>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="0">
                <el-col :span="24">
                  <el-form-item prop="lecturerStatus" label="审核状态">
                    <el-radio v-model="form.lecturerStatus" :label="0">预设</el-radio>
                    <el-radio v-model="form.lecturerStatus" :label="1">发布</el-radio>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="0">
                <el-col :span="24">
                  <el-form-item prop="lecturerIntroduction" label="讲师简介">
                    <el-input placeholder="请输入讲师文本简介" v-model="form.lecturerIntroduction" class="filter-item" auto-complete="off" type="textarea" :rows="4"/>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-col>
            <el-col :span="9">
              <el-row :gutter="0">
                <el-col :span="24">
                  <el-form-item prop="lecturerImage" label="讲师头像">
                    <el-upload
                      class="avatar-uploader"
                      action="/api/cms/common/uploadFile"
                      :show-file-list="false"
                      :on-success="handleImageUploadSuccess">
                      <img v-if="form.lecturerImage" :src="form.lecturerImage" class="avatar">
                      <i v-else class="el-icon-plus avatar-uploader-icon" style="line-height: 175px"></i>
                    </el-upload>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-col>
          </el-row>
          <el-row :gutter="0">
            <el-col :span="24">
              <vue-ueditor-wrap v-model="form.lecturerIntroductionHtml" :config="pageData.editorConfig"></vue-ueditor-wrap>
            </el-col>
          </el-row>
          <el-row :gutter="0">
            <el-col :span="24">
              <el-form-item>
                <el-button type="primary" @click.native.prevent="handleSaveButtonClick('form')">发布讲师</el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-dialog>
    </div>
  </div>
</template>

<script>
  // 组件引入
  // 方法工具引入
  import { PermissionsToDetectFormUser } from '@/utils/PermissionsDetect';
  import { getPermission } from '@/utils/UserCookies';
  // 接口引入
  import { loadCmsTeacherList,batchReleaseCmsTeacherData,saveCmsTeacherData,updateCmsTeacherData } from "@/api/content";
  export default {
    name: "login",
    //import引入的组件需要注入到对象中才能使用
    components: {},
    data (){
      return {
        pageData:{
          searchStatusList: [
            {label: "发布状态", value: -1},
            {label: "下架", value: 0},
            {label: "发布", value: 1}
          ],// 发布状态预设项
          loading: false,
          checkPanelStatus: false,// 图片预览隐藏域
          checkPanelInfo: "",// 图片预览地址
          formPanelStatus: false,
          formPanelTitle: "",
          formPanelType: 0,
          editorConfig: {
            autoHeightEnabled: false,// 编辑器不自动被内容撑高
            initialFrameHeight: 240,// 初始容器高度
            initialFrameWidth: '100%'// 初始容器宽度
          },// 编辑器配置
        },// 页面配置数据
        form:{
          searchTitle: "",
          searchStatus: -1,
          pageNum: 1,// 表单--页码
          pageSize: 12,// 表单--页面
          total: 0,// 表单--总量
          selection: [],// 多选的内容

          lecturerId: "",
          lecturerName: "",
          lecturerStatus: 0,
          lecturerIntroduction: "",
          lecturerImage: "",
          lecturerIntroductionHtml: "",
        },// 页面表单
        formRules: {
          lecturerName: [{ required: true, validator:(rule, value, callback) => {
              if (value === ''){
                this.$message.warning("请输入讲师昵称");
                callback(new Error("请输入讲师昵称"));
              } else {
                callback();
              }
            },trigger: "blur" }],// 标题
          lecturerImage: [{ required: true, validator:(rule, value, callback) => {
              if (value === ''){
                this.$message.warning("请上传讲师头像");
                callback(new Error("请上传讲师头像"));
              } else {
                callback();
              }
            },trigger: "blur" }],// 标题
          lecturerStatus: [{ required: true, validator:(rule, value, callback) => {
              if (value === ''){
                this.$message.warning("请选择讲师发布状态");
                callback(new Error("请选择讲师发布状态"));
              } else {
                callback();
              }
            },trigger: "blur" }],// 标题
        },// 表单验证
        responseData: {
          tableList: [],// 页面表格数据
        },// 接口响应数据
      }
    },
    //监听属性 类似于data概念
    computed: {},
    //监控data中的数据变化
    watch: {},
    //方法集合
    methods: {
      // 事件函数
      handlePageInit(){
        this.form.pageNum = 1;
        this.pageData.loading = true;// 创建加载窗口
        this.loadCmsTeacherList();// 读取路由角色列表
      },// 页面初始化事件
      handleCurrentChange(val){
        this.form.pageNum = val;// 更换页码
        this.pageData.loading = true;// 创建加载窗口
        this.loadCmsTeacherList();// 读取路由角色列表
      },// 页码切换事件
      handleSizeChange(val){
        this.form.pageSize = val;// 更换页面大小
        this.pageData.loading = true;// 创建加载窗口
        this.loadCmsTeacherList();// 读取路由角色列表
      },// 页面size切换事件
      handleTableSelection(val){
        let list = [];// 初始化多选数组
        for (let i=0; i<val.length; i++){
          list.push(val[i].lecturerId);
        }// 遍历多选的列表，将ID拼入数组中
        this.form.selection = list;// 进行多选值的切换
      },// 表格多选事件
      handleOpenSavePage(){
        // 初始化表单
        this.form.lecturerId = "";
        this.form.lecturerName = "";
        this.form.lecturerStatus = 0;
        this.form.lecturerIntroduction = "";
        this.form.lecturerImage = "";
        this.form.lecturerIntroductionHtml = "";
        // 打开隐藏面板
        this.pageData.formPanelStatus = true;
        this.pageData.formPanelTitle = "新增讲师";
        this.pageData.formPanelType = 1;
      },// 跳转到新增页面
      handleCloseSavePage(){
        this.$confirm("确认关闭？").then(response => {
          // 清空表单
          this.form.lecturerId = "";
          this.form.lecturerName = "";
          this.form.lecturerStatus = 0;
          this.form.lecturerIntroduction = "";
          this.form.lecturerImage = "";
          this.form.lecturerIntroductionHtml = "";
          // 关闭面板
          this.pageData.formPanelStatus = false;
          this.pageData.formPanelTitle = "";
          this.pageData.formPanelType = 0;
        }).catch(err => {
          console.log(err);
        });
      },// 关闭面板提示
      handleBatchReleaseData(){
        if (PermissionsToDetectFormUser(getPermission(), "430005")){
          this.$confirm("是否发布当前所选数据?", "提示", {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            let param = {
              lecturerId: this.form.selection.toString(),
              lecturerStatus: 1
            };
            this.batchReleaseCmsTeacherData(param);
          }).catch(close => {
            console.log(close);
            this.$message.info("已取消操作");
          });
        } else {
          this.$message.warning('您的权限不足，无法使用此功能，请联系管理员');
        }
      },// 批量发布内容
      handleCheckInfo(scope){
        this.pageData.checkPanelStatus = true;
        this.pageData.checkPanelInfo = scope.row.lecturerImage;
      },// 预览图像(查看表格详情)
      handleOpenEditPage(scope){
        if (PermissionsToDetectFormUser(getPermission(), "430003")){
          // 初始化表单
          this.form.lecturerId = scope.row.lecturerId;
          this.form.lecturerName = scope.row.lecturerName;
          this.form.lecturerStatus = scope.row.lecturerStatus;
          this.form.lecturerIntroduction = scope.row.lecturerIntroduction;
          this.form.lecturerImage = scope.row.lecturerImage;
          this.form.lecturerIntroductionHtml = scope.row.lecturerIntroductionHtml;
          // 打开隐藏面板
          this.pageData.formPanelStatus = true;
          this.pageData.formPanelTitle = "编辑讲师";
          this.pageData.formPanelType = 2;
        } else {
          this.$message.warning('您的权限不足，无法使用此功能，请联系管理员');
        }
      },// 跳转到修改页
      handleUpdateDataStatus(scope, status){
        if (PermissionsToDetectFormUser(getPermission(), "430005")){
          this.$confirm("是否更改当前所选数据的发布状态?", "提示", {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            let param = {
              lecturerId: scope.row.lecturerId,
              lecturerStatus: status
            };
            this.batchReleaseCmsTeacherData(param);
          }).catch(close => {
            console.log(close);
            this.$message.info("已取消操作");
          });
        } else {
          this.$message.warning('您的权限不足，无法使用此功能，请联系管理员');
        }
      },// 发布/下架内容
      handleDeleteData(scope){
        this.$message.info("该功能暂未开放，如有需要请联系管理员");
      },// 删除内容数据
      handleImageUploadSuccess(response){
        this.form.lecturerImage = response.data;
      },// 讲师头像上传成功
      handleSaveButtonClick(){
        if (this.pageData.formPanelType === 1){
          if (!PermissionsToDetectFormUser(getPermission(), "430001")){
            this.$message.warning('您的权限不足，无法使用此功能，请联系管理员');
            return;
          }
        }
        if (this.pageData.formPanelType === 2){
          if (!PermissionsToDetectFormUser(getPermission(), "430003")){
            this.$message.warning('您的权限不足，无法使用此功能，请联系管理员');
            return;
          }
        }
        this.$confirm('确认保存当前数据?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          if (this.pageData.formPanelType === 1) {
            this.saveCmsTeacherData();
          } else if (this.pageData.formPanelType === 2){
            this.updateCmsTeacherData();
          }
        }).catch(close => {
          console.log(close);
          this.$message.info("已取消操作");
        });
      },// 保存按钮点击事件
      // 接口
      loadCmsTeacherList(){
        loadCmsTeacherList(this.form).then(response => {
          if (response.code === "200"){
            this.pageData.loading = false;
            this.responseData.tableList = response.data.list;
            this.form.total = response.data.total;
          } else {
            this.$message.warning(response.message);
          }
        }).catch( error =>{
          console.log(error);
          this.$message.error(error);
        })
      },// 获取讲师列表
      batchReleaseCmsTeacherData(param){
        batchReleaseCmsTeacherData(param).then(response => {
          if (response.code === "200"){
            this.$message.success(param.lecturerStatus === 1 ? "发布成功" : "下架成功");
            this.handlePageInit();
          } else {
            this.$message.warning(response.message);
          }
        }).catch(close => {
          console.log(close);
        });
      },// 修改内容发布状态
      saveCmsTeacherData(){
        saveCmsTeacherData(this.form).then(response => {
          if (response.code === "200"){
            // 清空表单
            this.form.lecturerId = "";
            this.form.lecturerName = "";
            this.form.lecturerStatus = 0;
            this.form.lecturerIntroduction = "";
            this.form.lecturerImage = "";
            this.form.lecturerIntroductionHtml = "";
            // 关闭面板
            this.pageData.formPanelStatus = false;
            this.pageData.formPanelTitle = "";
            this.pageData.formPanelType = 0;
            this.$message.success("保存成功");
            this.handlePageInit();
          } else {
            this.$message.warning(response.message);
          }
        }).catch(close => {
          console.log(close);
        });
      },// 保存讲师数据
      updateCmsTeacherData(){
        updateCmsTeacherData(this.form).then(response => {
          if (response.code === "200"){
            // 清空表单
            this.form.lecturerId = "";
            this.form.lecturerName = "";
            this.form.lecturerStatus = 0;
            this.form.lecturerIntroduction = "";
            this.form.lecturerImage = "";
            this.form.lecturerIntroductionHtml = "";
            // 关闭面板
            this.pageData.formPanelStatus = false;
            this.pageData.formPanelTitle = "";
            this.pageData.formPanelType = 0;
            this.$message.success("保存成功");
            this.handlePageInit();
          } else {
            this.$message.warning(response.message);
          }
        }).catch(close => {
          console.log(close);
        });
      },// 修改讲师数据
    },
    //生命周期 - 创建完成（可以访问当前this实例）
    created: function(){
      let _this = this;
      document.onkeydown = function(e) {
        if (!_this.pageData.loading) {
          let key = window.event.keyCode;
          if (key === 13) {
            _this.handlePageInit(); //此方法是当按下enter键后要做的动作。
          }
        }
      };
      setTimeout(function () {
        _this.handlePageInit();
      }, 800);
    },
    //生命周期 - 挂载完成（可以访问DOM元素）
    mounted() {},
    beforeCreate() {}, //生命周期 - 创建之前
    beforeMount() {}, //生命周期 - 挂载之前
    beforeUpdate() {}, //生命周期 - 更新之前
    updated() {}, //生命周期 - 更新之后
    beforeDestroy() {}, //生命周期 - 销毁之前
    destroyed() {}, //生命周期 - 销毁完成
    activated() {}, //如果页面有keep-alive缓存功能，这个函数会触发
  }
</script>

<style rel="stylesheet/scss" lang="scss">
</style>
